# 13. 常用的js函数

# 浅拷贝

function extend (a, b) {
  for (const key in b) {
    a[key] = b[key]
  }
  return a
}
1
2
3
4
5
6

# 深拷贝

function clone (value) {
  if (Array.isArray(value)) {
    return value.map(clone)
  } else if (value && typeof value === 'object') {
    const res = {}
    for (const key in value) {
      res[key] = clone(value[key])
    }
    return res
  } else {
    return value
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 判断对象是否相等

function isObjectEqual (a = {}, b = {}): boolean {
  // handle null value #1566
  if (!a || !b) return a === b
  const aKeys = Object.keys(a)
  const bKeys = Object.keys(b)
  if (aKeys.length !== bKeys.length) {
    return false
  }
  return aKeys.every(key => {
    const aVal = a[key]
    const bVal = b[key]
    // check nested equality
    if (typeof aVal === 'object' && typeof bVal === 'object') {
      return isObjectEqual(aVal, bVal)
    }
    return String(aVal) === String(bVal)
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 异步执行

function runQueue (queue: Array, fn: Function, cb: Function) {
  const step = index => {
    if (index >= queue.length) {
      cb()
    } else {
      if (queue[index]) {
        fn(queue[index], () => {
          step(index + 1)
        })
      } else {
        step(index + 1)
      }
    }
  }
  step(0)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

测试:

const calls = []
const queue = [1, 2, 3, 4, 5].map(i => next => {
  calls.push(i)
  console.log(i);
  setTimeout(next, 2000)
})
runQueue(queue, (fn, next) => fn(next), () => {
  console.log(calls)
})

// 15:59:12.079 1
// 15:59:14.067 2
// 15:59:16.071 3
// 15:59:18.073 4
// 15:59:20.077 5
// 15:59:22.079 [1, 2, 3, 4, 5]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 重写window.Date,和服务器时间一致

$axios.get('/getServerDate').then(res => {
  let serverDate = new Date(res.headers.date);
  let difference = serverDate - new Date();
  let temp = window.Date;
  window.Date = function() {
    if (arguments.length) {
      return new temp(...arguments);
    } else {
      return new temp(difference + new temp().getTime());
    }
  }
  window.Date.prototype = temp.prototype;
  window.Date.parse = temp.parse;
  window.Date.now = function() {
    return Date().getTime();
  };
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17